<template>
  <div>
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- 1. 搜索区域 输入框 -->
    <van-search
      @input="throttleInter"
      v-model.trim="keyword"
      show-action
      placeholder="请输入搜索关键词"
    >
      <div
        slot="action"
        @click="hSearch"
      >搜索</div>
    </van-search>

    <!-- 2. 搜索建议 -->
    <van-cell-group v-if="suggestions.length">
      <van-cell
        v-for="(item, idx) in cSuggestions"
        :key="idx"
        icon="search"
        @click="hClickSuggetion(idx)"
      >
        <div v-html="item"></div>
      </van-cell>
    </van-cell-group>

    <!-- 3. 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录" />

      <van-cell
        v-for="(history, idx) in historys"
        :key="idx"
        :title="history"
        @click="$router.push('/result?keyword=' + item)"
      >
        <van-icon name="close"
          @click.stop="hDelHistory(idx)"
        ></van-icon>
      </van-cell>

    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search.js'
import { getHistory, setHistory } from '@/utils/storageHistory.js'
import { throttle } from '@/utils/tools.js'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      suggestions: [],
      historys: getHistory() || []
    }
  },
  methods: {
    // 在前边添加搜索记录
    addHistory (keyword) {
      const idx = this.historys.indexOf(keyword)
      if (idx !== -1) {
        this.historys.splice(idx, 1)
      }
      this.historys.unshift(keyword)
      setHistory(this.historys)
    },
    // 点击搜索调用添加
    hSearch () {
      if (this.keyword === '') {
        return
      }
      this.addHistory(this.keyword)
      this.$router.push('/result?keyword=' + this.keyword)
    },
    // 点击搜索建议添加
    hClickSuggetion (idx) {
      this.addHistory(this.suggestions[idx])
      this.$router.push('/result?keyword=' + this.suggestions[idx])
    },
    // 点击是叉号删除搜索记录
    hDelHistory (idx) {
      this.historys.splice(idx, 1)
      setHistory(this.historys)
    },
    throttleInter: throttle(function () {
      this.hInput()
    }, 500),
    async hInput () {
      if (this.keyword === '') {
        this.suggestions = []
        return
      }
      try {
        const res = await getSuggestion(this.keyword)
        console.log(res)
        this.suggestions = res.data.data.options
      } catch (err) {
        console.log(err)
      }
    }
  },
  computed: {
    cSuggestions () {
      const reg = new RegExp(this.keyword, 'gi')
      const newArray = this.suggestions.map(sug => {
        return sug.replace(reg, val => '<span style="color:red">' + val + '</span>')
      })
      return newArray
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-nav-bar .van-icon {
  color: #fff;
}
</style>
